package org.lztvn.elearning.front_controllers;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.lztvn.elearning.controllers.AppController;
import org.lztvn.elearning.entities.Contact;
import org.lztvn.elearning.entities.Product;
import org.lztvn.elearning.entities.Response;
import org.lztvn.elearning.entities.StudentTest;
import org.lztvn.elearning.entities.Test1;
import org.lztvn.elearning.entities.Topic;
import org.lztvn.elearning.entities.User;
import org.lztvn.elearning.service.IResponseService;
import org.lztvn.elearning.service.ITopicService;
import org.lztvn.elearning.service.JsonResponse;
import org.lztvn.elearning.service.Utility;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.validation.ValidationUtils;

@Controller
@RequestMapping(value = "/forum")
@SessionAttributes("userFLogin")
public class ForumController extends AppController{
	@Autowired
	ITopicService serviceTopic;
	@Autowired
	IResponseService serviceRes;
	
	Utility util;
	JsonResponse jresp;
	private static int nbLigns=3;
	
	private void init() {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		this.util = (Utility) context.getBean("util");
		this.jresp = (JsonResponse) context.getBean("json");
	}
	
	@RequestMapping(value = "/index")
	public String index(Model model,  HttpSession session) {
		init();
		if (util.checkFrontSession(session) == false) {
			model.addAttribute("user", new User());
			return ("redirect:../lstcourses/login");
		}
		else{
			model.addAttribute("forum", new Topic());
			return "forum";
		}
	}
	
	@RequestMapping(value="/save_msg", method=RequestMethod.POST)
	public @ResponseBody JsonResponse  saveRespond(@ModelAttribute(value="res") Response res, BindingResult result){
		ValidationUtils.rejectIfEmpty(result, "answer", "Message can not be empty.");
     
		if(!result.hasErrors()){
			res.setDateMsg(new Date());
			serviceRes.addResponse(res);
			jresp.setStatus("SUCCESS");
			jresp.setResult(res);

        }else{
        	jresp.setStatus("FAIL");
        	jresp.setResult(result.getAllErrors());

        }
		return jresp;
	}
	
	
	@RequestMapping(value = "/del_resp", method=RequestMethod.GET)
	public @ResponseBody JsonResponse del(Long idResponse, HttpSession session) {
		
			serviceRes.deleteResponse(idResponse);
			jresp.setStatus("DEL_SUCCESS");
			return jresp;
		
	}
	
	@RequestMapping(value = "/topic_view")
	public String topic_view(Long idt, Model model,  HttpSession session) {
		init();
		if (util.checkFrontSession(session) == false) {
			model.addAttribute("user", new User());
			return ("redirect:../lstcourses/login");
		}else{
			model.addAttribute("topic", serviceTopic.getTopic(idt));
			model.addAttribute("list_resp", serviceRes.listResponseByTopicId(idt, 0, 0));
			model.addAttribute("respond", new Response());
			return "topic_view"; 
		}
	}
	
	
	@RequestMapping(value = "/delTopic/{idTopics}/{page}", method = RequestMethod.GET)
	public String delTopic(@PathVariable Long idTopics,@PathVariable Long page, Model model,HttpSession session) {
		init();
		if (util.checkFrontSession(session) == false) {
			model.addAttribute("user", new User());
			return ("redirect:../lstcourses/login");
		}else{
			
			serviceTopic.deleteTopic(idTopics);
			int pos=0;
			if(page!=null){
	        pos = (int) (nbLigns*page);
	        model.addAttribute("page", page);
			}
			else{
				model.addAttribute("page", 1);
			}
			
			
			model.addAttribute("list_topic", serviceTopic.listTopic(pos,nbLigns));
			Long nbTopic = serviceTopic.getNbTopic();
			model.addAttribute("nbPage", (nbTopic/nbLigns) + 1);
			return ( "list_topic_view");
		}
		
		
		
	}
	
	
	@RequestMapping(value = "/list_topic", method = RequestMethod.GET)
	public ModelAndView list_topic(Long page,Model model,  HttpSession session) {
		int pos=0;
		if(page!=null){
        pos = (int) (nbLigns*page);
        model.addAttribute("page", page);
		}
		else{
			model.addAttribute("page", 1);
		}
		
		
		model.addAttribute("list_topic", serviceTopic.listTopic(pos,nbLigns));
		Long nbTopic = serviceTopic.getNbTopic();
		model.addAttribute("nbPage", (nbTopic/nbLigns) + 1);
		return new ModelAndView( "list_topic_view");
		
	}
	
	@RequestMapping(value="saveForum", method=RequestMethod.POST)
	public String saveForum(@Valid Topic t, Model model, BindingResult bindingResult, final RedirectAttributes redirectAttributes){
		if (bindingResult.hasErrors()) {
			model.addAttribute("forum", new Topic());
			return ("forum");
		}
		t.setDateMsg(new Date());
		serviceTopic.addTopic(t);
		redirectAttributes.addFlashAttribute("page", 0);
		return "redirect:../forum/list_topic";
	}
	
	
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object arg2, Exception ex) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("topic", new Topic());
		mv.addObject("exception", ex.getMessage());
		mv.setViewName("topic");
		return mv;
	}

}
